package com.xiguthings.waka.web.controller.growth;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.xiguthings.waka.po.Paper;
import com.xiguthings.waka.po.PaperExample;
import com.xiguthings.waka.service.paper.IPaperService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiguthings.waka.dao.DataBaseStatus;
import com.xiguthings.waka.exception.BussinessException;
import com.xiguthings.waka.po.Growth;
import com.xiguthings.waka.po.GrowthExample;
import com.xiguthings.waka.po.GrowthExample.Criteria;
import com.xiguthings.waka.po.extpo.GrowthExt;
import com.xiguthings.waka.po.extpo.Page;
import com.xiguthings.waka.publicUtils.StringUtils;
import com.xiguthings.waka.service.growth.IGrowthService;
import com.xiguthings.waka.web.controller.base.AbstractController;
import com.xiguthings.waka.web.controller.base.ResponseEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@Controller
@RequestMapping("/growth")
@Api(tags = "成长维度")
public class GrowthController extends AbstractController {

	@Resource
	// @Autowired
	private IGrowthService growthService;
	@Resource
	private IPaperService paperService;
	/**
	 * 创建查询条件
	 * 
	 * @param growthVo
	 * @param example
	 * @throws NumberFormatException
	 */
	private void queryConditions(GrowthVo growthVo, GrowthExample example) throws NumberFormatException {
		Criteria criteria = example.createCriteria();
		// 如果查询条件为空的
		if (growthVo == null) {
			// 则查询所有未被删除的
			criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
			return;
		}

		// 如果有查询条件
		Growth growth = growthVo.getGrowth();
		// 添加查询条件
		if (growth != null) {
			if (StringUtils.isNotBlank(growth.getGrowthId())) {
				criteria.andGrowthIdEqualTo(growth.getGrowthId());
			}
			if (StringUtils.isNotBlank(growth.getName())) {
				criteria.andNameLike("%" + growth.getName() + "%");
			}
			if (StringUtils.isNotBlank(growth.getDescr())) {
				criteria.andDescrLike(("%" + growth.getDescr() + "%"));
			}
		}

		if (StringUtils.isNotBlank(growthVo.getInStatus())) {
			// 添加包含的状态
			String statuses = growthVo.getInStatus();
			String[] statusArr = statuses.split(",");
			List<Integer> statusList = new ArrayList<>();
			for (String str : statusArr) {
				statusList.add(new Integer(str));
			}
			criteria.andStatusIn(statusList);
		} else {
			// 如果状态的查询条件是空的，则查询没有被删除的
			criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
		}

	}

	// /**
	// * 获取总数
	// *
	// * @param growthVo
	// * @return
	// * @throws Exception
	// */
	// @ApiOperation(tags = { "1.控制台",
	// "2.用户端" }, value = "获取总数", httpMethod = "POST", notes = "可根据条件查询",
	// response = ResponseEntity.class)
	// @ApiImplicitParams({
	// @ApiImplicitParam(name = "growth.growthId", value = "主键id", dataType =
	// "String", required = false, paramType = "query"),
	// @ApiImplicitParam(name = "growth.name", value = "名称", dataType =
	// "string", required = false, paramType = "query"),
	// @ApiImplicitParam(name = "growth.descr", value = "描述信息", dataType =
	// "string", required = false, paramType = "query"),
	// @ApiImplicitParam(name = "inStatus", value =
	// "状态：0--正常，99--删除;多个值用英文逗号分隔", dataType = "string", required = false,
	// paramType = "query"), })
	// @RequestMapping("/count")
	// @ResponseBody
	// public ResponseEntity count(@ApiIgnore GrowthVo growthVo) throws
	// Exception {
	// GrowthExample example = new GrowthExample();
	// queryConditions(growthVo, example);
	// int count = this.growthService.count(example);
	// return ajaxReturnMap(CODE_SUCCESS, null, count);
	// }

	/**
	 * 修改或者添加
	 * 
	 * @param growthVo
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(tags = {
			"1.控制台" }, value = "修改/添加", httpMethod = "POST", notes = "修改时，必须填写“growth.growthId”参数", response = ResponseEntity.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "growth.growthId", value = "主键id", dataType = "String", required = false, paramType = "query"),
			@ApiImplicitParam(name = "growth.name", value = "名称", dataType = "string", required = false, paramType = "query"),
			@ApiImplicitParam(name = "growth.descr", value = "描述信息", dataType = "string", required = false, paramType = "query"),
			@ApiImplicitParam(name = "growth.status", value = "状态：0--正常，99--删除", dataType = "int", required = false, paramType = "query"), })
	@RequestMapping("/save")
	@ResponseBody
	public ResponseEntity save(@ApiIgnore GrowthVo growthVo) throws Exception {

		if (growthVo == null || growthVo.getGrowth() == null) {
			BussinessException bet = new BussinessException("空参数");
			bet.setCode(CODE_EMPTY_REQUIRED);
			throw bet;
		}

		String msg = "";
		Growth growth = growthVo.getGrowth();
		if (StringUtils.isNotBlank(growth.getGrowthId())) {
			// updata
			growthService.updateByPrimaryKeySelective(growth);
			msg = "修改成功";
		} else {
			// insert
			growthService.insert(growthVo.getGrowth());
			msg = "添加成功";
		}
		String id = growth.getGrowthId();
		return ajaxReturnMap(CODE_SUCCESS, msg, id);
	}

	@ApiOperation(tags = { "1.控制台",
			"2.用户端" }, value = "根据主键获取记录详情", httpMethod = "GET", notes = "gowthId是必填", response = ResponseEntity.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "growth.growthId", value = "主键id", dataType = "String", required = true, paramType = "query"),
			@ApiImplicitParam(name = "associated", value = "是否关联查询,true--关联查询,默认是false", dataType = "boolean", required = false, paramType = "query") })
	@RequestMapping("/detail")
	@ResponseBody
	public ResponseEntity detail(@ApiIgnore GrowthVo growthVo) throws Exception {
		String growthId = null;
		if (growthVo != null && growthVo.getGrowth() != null
				&& StringUtils.isBlank((growthId = growthVo.getGrowth().getGrowthId()))) {
			BussinessException bet = new BussinessException("growthId是空参数");
			bet.setCode(CODE_EMPTY_REQUIRED);
			throw bet;
		}

		Growth growth = null;
		if (growthVo.isAssociated() == true) {
			growth = growthService.selectByPrimaryKeyWithAssociated(growthId);
		} else {
			growth = growthService.selectByPrimaryKey(growthId);
		}
		return ajaxReturnMap(CODE_SUCCESS, "", growth);
	}

	@ApiOperation(tags = { "1.控制台",
			"2.用户端" }, value = "根据主键获取记录详情", httpMethod = "GET", notes = "gowthId是必填", response = ResponseEntity.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "growth.growthId", value = "主键id,如果有多个，请用英文逗号分隔", dataType = "String", required = true, paramType = "query") })
	@RequestMapping("/delete")
	@ResponseBody
	public ResponseEntity delete(@ApiIgnore GrowthVo growthVo) throws Exception {
		//TODO
		return null;
	}

	/**
	 * 分页查询
	 * 
	 * @param growthVo
	 * @param page
	 * @return
	 * @throws Exception
	 */

	@ApiOperation(tags = {"1.控制台",
			"2.用户端"}, value = "分页查询", httpMethod = "GET", notes = "可根据条件进行筛选", response = ResponseEntity.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "growth.growthId", value = "主键id", dataType = "String", required = false, paramType = "query"),
			@ApiImplicitParam(name = "growth.name", value = "名称", dataType = "string", required = false, paramType = "query"),
			@ApiImplicitParam(name = "growth.descr", value = "描述信息", dataType = "string", required = false, paramType = "query"),
			@ApiImplicitParam(name = "inStatus", value = "状态：0--正常，99--删除", dataType = "int", required = false, paramType = "query"),
			@ApiImplicitParam(name = "associated", value = "是否关联查询,true--关联查询,默认是false", dataType = "boolean", required = false, paramType = "query"),
			@ApiImplicitParam(name = "inPaperStatus", value = "关联查询时，需要限制的paper状态,多个值就用引文逗号分隔", dataType = "string", required = false, paramType = "query"),
			@ApiImplicitParam(name = "inPaperRank", value = "关联查询时，需要限制的paper排序号,多个值就用引文逗号分隔", dataType = "string", required = false, paramType = "query"),
			@ApiImplicitParam(name = "page", value = "页码，如果没有值，则使用默认值。开始值从 1 开始计算", dataType = "int", required = false, paramType = "query"),
			@ApiImplicitParam(name = "rows", value = "每页的数量,如果没有值，则使用默认值", dataType = "int", required = false, paramType = "query")})
	@RequestMapping("/pagelist")
	@ResponseBody
	public ResponseEntity pageList(@ApiIgnore GrowthVo growthVo, @ApiIgnore Page page, @ApiIgnore String inPaperStatus, @ApiIgnore String inPaperRank) throws Exception {

		GrowthExample growthExample = new GrowthExample();
		queryConditions(growthVo, growthExample);
		super.selectByPage(page, growthExample, growthService);// 分页查询growth
		// 如果结果空的，直接返回
		if (page == null || page.getList() == null || page.getList().size() < 1) {
			return ajaxReturnMap(CODE_SUCCESS, null, page);
		}


		//如不需要关联查询，就直接返回结果
		if (growthVo == null || growthVo.isAssociated() == false) {
			return ajaxReturnMap(CODE_SUCCESS, null, page);
		}


		// 关联查询
		List<GrowthExt> GrowthExtList = new ArrayList<>();
		List<Growth> growthList = (List<Growth>) page.getList();
		for (Growth growth : growthList) {
			PaperExample paperExample = new PaperExample();
			PaperExample.Criteria criteria = paperExample.createCriteria().andGrowthIdEqualTo(growth.getGrowthId());// 根据growthId查询

			// 如果需要限制查询paper的状态
			if (StringUtils.isNotBlank(inPaperStatus)) {
				// 添加限制paper状态的条件
				List<Integer> list = new ArrayList<>();
				for (String paperStatusStr : StringUtils.listBySplit(inPaperStatus, ",")) {
					list.add(new Integer(paperStatusStr));
				}
				criteria.andStatusIn(list);
			}

			// 如果需要限制paper的rank
			if (StringUtils.isNotBlank(inPaperRank)) {
				// 添加限制paper状态的rank
				List<Integer> list = new ArrayList<>();
				for (String paperStatusStr : StringUtils.listBySplit(inPaperRank, ",")) {
					list.add(new Integer(paperStatusStr));
				}
				criteria.andRankIn(list);
			}

			// 查询数据
			List<Paper> papers = paperService.selectByExample(paperExample);
			GrowthExt growthExt = new GrowthExt();
			BeanUtils.copyProperties(growth, growthExt);
			growthExt.setPaperList(papers);
			GrowthExtList.add(growthExt);
		}
		page.setList(GrowthExtList);

		return ajaxReturnMap(CODE_SUCCESS, null, page);
	}
}
